<template>
  <div class="mt-3 flex w-full">
    <div class="mr-3 flex-1">
      <a-form layout="inline">
        <a-form-item label="所属机构" :model="searchForm">
          <a-tree-select
            v-model:value="searchForm.companyNode"
            tree-node-filter-prop="label"
            style="width: 260px"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :tree-data="comanyList"
            placeholder="请选择归属机构"
            @change="onComany"
            allowClear
          />
        </a-form-item>
        <a-form-item label="小区">
          <a-select
            style="width: 150px"
            placeholder="请选择小区"
            :options="villageList"
            v-model:value="searchForm.villageNode"
            @change="onBuilding"
            allowClear
          />
        </a-form-item>
        <a-form-item label="楼栋">
          <a-select
            style="width: 150px"
            placeholder="请选择楼栋"
            :options="buildingList"
            v-model:value="searchForm.buildingNode"
            allowClear
            @change="onHeating"
          />
        </a-form-item>
        <a-form-item label="单元">
          <a-select
            style="width: 150px"
            placeholder="请选择单元"
            :options="heatingList"
            v-model:value="searchForm.targetUnitId"
            allowClear
          />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="onSearch"
            ><SearchOutlined />查询</a-button
          >
        </a-form-item>
        <a-form-item>
          <a-button
            type="primary"
            @click="onAction"
            :disabled="selectedRowKeys.length <= 0"
            ><SwapOutlined />确认迁移</a-button
          >
        </a-form-item>
      </a-form>
      <a-table
        :columns="columns"
        :data-source="dataSource"
        :pagination="pagination"
        class="mt-3"
        rowKey="houseID"
        :row-selection="{
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange,
        }"
      />
    </div>
    <div class="ml-3 flex-1">
      <a-form layout="inline" :model="searchForm2">
        <a-form-item label="迁移类型">
          <a-select
            style="width: 150px"
            placeholder="请选择所属机构"
            v-model:value="searchForm2.migrationType"
          >
            <a-select-option value="小区">小区</a-select-option>
            <a-select-option value="楼栋">楼栋</a-select-option>
            <a-select-option value="单元">单元</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="小区" v-if="searchForm2.migrationType === '小区'">
          <a-select
            style="width: 150px"
            placeholder="请选择小区"
            :options="villageList"
            v-model:value="searchForm2.villageNode"
            allowClear
            @change="onBuilding"
          />
        </a-form-item>
        <a-form-item label="楼栋" v-if="searchForm2.migrationType === '楼栋'">
          <a-select
            style="width: 150px"
            placeholder="请选择楼栋"
            :options="buildingList"
            v-model:value="searchForm2.buildingNode"
            allowClear
            @change="onHeating"
          />
        </a-form-item>
        <a-form-item label="单元" v-if="searchForm2.migrationType === '单元'">
          <a-select
            style="width: 150px"
            placeholder="请选择单元"
            :options="heatingList"
            v-model:value="searchForm2.targetUnitId"
            allowClear
          />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="onSearch2"
            ><SwapOutlined />迁移预览</a-button
          >
        </a-form-item>
      </a-form>
      <a-table
        :columns="columns2"
        :data-source="dataSource2"
        :pagination="pagination2"
        class="mt-3"
      />
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue';
import { SwapOutlined, SearchOutlined } from '@ant-design/icons-vue';
import {
  getBelongingInstitution,
  getBelongingInstitutionVillage,
  getBelongingInstitutionBuilding,
  getBelongingInstitutionHouse,
  getBelongingInstitutionHouseName,
  getBelongingInstitutionHouseName_two,
  getHouseMigrationInformationPage,
} from '#/api/core/customerInformation';
import { message } from 'ant-design-vue';

const searchForm = reactive({
  companyNode: '',
  villageNode: '',
  buildingNode: '',
  targetUnitId: '',
  migrationType: '',
});
const searchForm2 = reactive({
  companyNode: '',
  villageNode: '',
  buildingNode: '',
  targetUnitId: '',
  migrationType: '',
});
const comanyList = ref([]);
const getComanyList = () => {
  getBelongingInstitution().then((res: any) => {
    console.log(res);
    // 递归处理树形数据，保持层级结构
    const processTreeData = (tree: any[]): any[] => {
      // console.log(tree)
      return tree.map((item: any) => {
        const processedItem = {
          key: item.id,
          label: item.title,
          level: item.level,
          value: item.id,
          isLeaf: item.children && item.children.length > 0 ? false : true,
          children: [],
        };

        // 如果存在children，递归处理子节点
        if (item.children && item.children.length > 0) {
          processedItem.children = processTreeData(item.children);
        }

        return processedItem;
      });
    };

    const treeData = processTreeData([res.data]);
    comanyList.value = treeData;
  });
};
getComanyList();
const villageList = ref([]);
const buildingList = ref([]);
const heatingList = ref([]);
const selectedRowKeys = ref<any[]>([]);
const getVillageList = (companyNode: any) => {
  getBelongingInstitutionVillage(companyNode).then((res: any) => {
    console.log(res);
    villageList.value = res.data.data.map((item) => {
      return {
        label: item.title,
        value: item.id,
      };
    });
  });
};
const onBuilding = (e: any) => {
  getBelongingInstitutionBuilding(e).then((res: any) => {
    console.log(res);
    buildingList.value = res.data.data.map((item) => {
      return {
        label: item.title,
        value: item.id,
      };
    });
  });
};
const onHeating = (e: any) => {
  getBelongingInstitutionHouse(e).then((res: any) => {
    console.log(res);
    heatingList.value = res.data.data.map((item) => {
      return {
        label: item.title,
        value: item.id,
      };
    });
  });
};
const onComany = (e: any) => {
  console.log(e);
  getVillageList(e);
};
const dataSource = ref([]);
const columns = [
  {
    title: '小区名称',
    dataIndex: 'village',
    key: 'village',
    align: 'center',
  },
  {
    title: '楼栋',
    dataIndex: 'building',
    key: 'building',
    align: 'center',
  },
  {
    title: '单元',
    dataIndex: 'unit',
    key: 'unit',
    align: 'center',
  },
  {
    title: '房间号',
    dataIndex: 'house',
    key: 'house',
    align: 'center',
  },
];
const pagination = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    pagination.current = page;
    pagination.pageSize = pageSize;
    onSearch();
  },
});
const dataSource2 = ref([]);
const columns2 = [
  {
    title: '小区名称',
    dataIndex: 'village',
    key: 'village',
    align: 'center',
  },
  {
    title: '楼栋',
    dataIndex: 'building',
    key: 'building',
    align: 'center',
  },
  {
    title: '单元',
    dataIndex: 'unit',
    key: 'unit',
    align: 'center',
  },
  {
    title: '房间号',
    dataIndex: 'house',
    key: 'house',
    align: 'center',
  },
];
const pagination2 = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    pagination.current = page;
    pagination.pageSize = pageSize;
    onSearch2();
  },
});
const onSelectChange = (Keys: any[]) => {
  selectedRowKeys.value = Keys;
  console.log(selectedRowKeys.value);
};
const onSearch = () => {
  getBelongingInstitutionHouseName({
    villageNode: searchForm.villageNode,
    buildingNode: searchForm.buildingNode,
    unitNode: searchForm.targetUnitId,
  }).then((res: any) => {
    console.log(res);
    dataSource.value = res.data.data.data;
    pagination.total = res.data.data.count;
  });
};
const onSearch2 = () => {
  if (searchForm2.migrationType == '小区') {
    getBelongingInstitutionHouseName_two({
      migrationType: searchForm2.migrationType,
      houseIds: selectedRowKeys.value,
      targetVillageId: searchForm2.villageNode,
    }).then((res: any) => {
      // console.log(res);
      dataSource2.value = res.data.data.data;
      pagination2.total = res.data.data.count;
    });
  } else if (searchForm2.migrationType == '楼栋') {
    getBelongingInstitutionHouseName_two({
      migrationType: searchForm2.migrationType,
      houseIds: selectedRowKeys.value,
      targetVillageId: searchForm2.villageNode,
      targetBuildingId: searchForm2.buildingNode,
    }).then((res: any) => {
      dataSource2.value = res.data.data.data;
      pagination2.total = res.data.data.count;
    });
  } else if (searchForm2.migrationType == '单元') {
    getBelongingInstitutionHouseName_two({
      migrationType: searchForm2.migrationType,
      houseIds: selectedRowKeys.value,
      targetVillageId: searchForm2.villageNode,
      targetBuildingId: searchForm2.buildingNode,
      targetUnitId: searchForm2.targetUnitId,
    }).then((res: any) => {
      dataSource2.value = res.data.data.data;
      pagination2.total = res.data.data.count;
    });
  }
};
const onAction = () => {
  if (searchForm2.migrationType == '小区') {
    getHouseMigrationInformationPage({
      migrationType: searchForm2.migrationType,
      houseIds: selectedRowKeys.value,
      targetVillageId: searchForm2.villageNode,
    }).then((res: any) => {
      if (res.data.data.code == 200) {
        message.success(res.data.data.data);
        onSearch2();
      } else {
        message.error('迁移失败');
      }
    });
  } else if (searchForm2.migrationType == '楼栋') {
    getHouseMigrationInformationPage({
      migrationType: searchForm2.migrationType,
      houseIds: selectedRowKeys.value,
      targetVillageId: searchForm2.villageNode,
      targetBuildingId: searchForm2.buildingNode,
    }).then((res: any) => {
      if (res.data.data.code == 200) {
        message.success(res.data.data.data);
        onSearch2();
      } else {
        message.error('迁移失败');
      }
    });
  } else if (searchForm2.migrationType == '单元') {
    getHouseMigrationInformationPage({
      migrationType: searchForm2.migrationType,
      houseIds: selectedRowKeys.value,
      targetVillageId: searchForm2.villageNode,
      targetBuildingId: searchForm2.buildingNode,
      targetUnitId: searchForm2.targetUnitId,
    }).then((res: any) => {
      if (res.data.data.code == 200) {
        message.success(res.data.data.data);
        onSearch2();
      } else {
        message.error('迁移失败');
      }
    });
  }
};
</script>
<style scoped>
:deep(.ant-form-item) {
  margin-bottom: 10px !important;
}
</style>
